﻿using HomeWork911.Api.Read.Appliaction.Commond;
using HomeWork911.Api.Read.Dto;
using HomeWork911.Domain;
using HomeWork911.ErrorCode;
using HomeWork911.infrastrunceture;
using MediatR;

namespace HomeWork911.Api.Read.Appliaction.CommondHandler
{
    public class ShowUserCommondHandler : IRequestHandler<ShowUserCommond, ApiResult<ApiPaging<LoginDto>>>
    {
        private readonly IBaseIRepository<Role> role;
        private readonly IBaseIRepository<User> user;
        private readonly IBaseIRepository<RoleUser> roleUser;

        public ShowUserCommondHandler(IBaseIRepository<Role> role, IBaseIRepository<User> user, IBaseIRepository<RoleUser> roleUser)
        {
            this.role = role;
            this.user = user;
            this.roleUser = roleUser;
        }
        public Task<ApiResult<ApiPaging<LoginDto>>> Handle(ShowUserCommond request, CancellationToken cancellationToken)
        {
            ApiResult<ApiPaging<LoginDto>> result = new ApiResult<ApiPaging<LoginDto>>();
            result.Code=ApiEnum.查询成功;
            result.Msg=ApiEnum.查询成功.ToString();
            var list = from a in user.GetAll()
                       join b in roleUser.GetAll() on a.UserId equals b.UserId
                       join c in role.GetAll() on b.RoleId equals c.RoleId
                       select new LoginDto()
                       {
                           UserId = a.UserId,
                           UserName = a.UserName,
                           UserNikename = a.UserNikename,
                           Password = a.Password,
                           Createtime=a.Createtime,
                           Number = a.Number,
                           State = a.State,
                           RoleId = c.RoleId,
                           RoleName = c.RoleName
                       };
            if(!string.IsNullOrEmpty(request.UsreName))
            {
                list = list.Where(x => x.UserName.Contains(request.UsreName));
            }
            var totoCount=list.Count();
            var totoPage = (int)Math.Ceiling(totoCount * 1.0 / request.Pagesize);
            list=list.OrderBy(x=>x.Number).Skip((request.Pageindex-1)*request.Pagesize).Take(request.Pagesize);
            ApiPaging< LoginDto > paging = new ApiPaging< LoginDto >();
            paging.totoPage = totoPage;
            paging.totoCount = totoCount;
            paging.data=list.ToList();
            result.data = paging;
            return Task.FromResult(result);
        }
    }
}
